package com.webchat.common.config.interceptor;


import com.webchat.common.config.annotation.ValidateLogin;
import com.webchat.common.config.properties.OauthProperties;
import com.webchat.common.enums.BaseErrCodeEnum;
import com.webchat.common.helper.SessionHelper;
import com.webchat.common.util.JsonUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Component
public class ValidateLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private OauthProperties oauthProperties;

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        // 检查 handler 是否为 HandlerMethod 类型
        if (!(handler instanceof HandlerMethod)) {
            // 不是 HandlerMethod 类型，可能是静态资源请求，直接放行
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获取拦截到的方法
        Method method = handlerMethod.getMethod();
        // 获取方法到的RequestPermission注解
        ValidateLogin validateLogin = method.getAnnotation(ValidateLogin.class);
        if (validateLogin == null) {
            // 未获取到登录鉴权注解，直接放行
            return true;
        }
        // 当前主线程副本中获取登录用户id
        String loginUserId = SessionHelper.getCurrentUserId();
        if (StringUtils.isNotBlank(loginUserId)) {
            // 说明用户已登录
            return true;
        }
        // 未登录，需要影响前端302到登录服务的信息
        this.unLogin(request, response);
        return false;
    }

    private void unLogin(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> responseMap = new HashMap<>();
        response.setCharacterEncoding("UTF-8"); // 设置字符编码为 UTF-8
        response.setContentType("application/json;charset=UTF-8"); // 设置内容类型和字符编码
        responseMap.put("code", BaseErrCodeEnum.UN_LOGIN.getCode());
        responseMap.put("message", BaseErrCodeEnum.UN_LOGIN.getMessage());
        responseMap.put("redirect_url", getRedirectUrl(request));
        try {
            response.getWriter().println(JsonUtil.toJsonString(responseMap));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String getRedirectUrl(HttpServletRequest request) {
        String serverUrl = oauthProperties.getServerUrl();
        String originUrl = request.getHeader("origin-url");
        return String.format(serverUrl, URLEncoder.encode(originUrl));
    }
}